package com.common.www.controller.base;

import com.common.www.bean.entity.Result;
import com.common.www.utils.R;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.Serializable;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

/**
 * @program: bianmaba-web-framework-extends
 * @description:
 * @author: Chenjiabin
 * @create: 2018-04-23 20:05
 **/
public abstract class DefaultCrudController<T, ID extends Serializable> extends DefaultReadController<T, ID> {


    @ApiOperation(value = "保存", notes = "参数为JSON数据对象")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Result<T> save(@RequestBody T entity) {
        return R.ok(getService().save(entity));
    }

    @ApiOperation(value = "批量删除", notes = "根据ID集批量删除，返回true表示删除成功")
    @ApiImplicitParam(name = "ids", value = "ids", dataType = "int", paramType = "query")
    @RequestMapping(value = "/deletes", method = RequestMethod.POST)
    public Result deletes(ID[] ids) {
        try {
            getService().delete(ids);
            return R.ok(null, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("删除失败");
        }
    }

    @ApiOperation(value = "删除", notes = "根据ID删除，返回true表示删除成功")
    @ApiImplicitParam(name = "id", value = "id", dataType = "int", paramType = "query")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Result delete(ID id) {
        try {
            getService().delete(id);
            return R.ok(null, "删除成功");
        } catch (Exception e) {
            return R.fail("删除失败");
        }
    }

    /**
     * 根据json得到实体对象
     */
    protected T getBeanByJson(String json, Class<T> tClass) {
        Object bean = com.alibaba.fastjson.JSON.parseObject(json, tClass);
        return (T) bean;
    }
}
